<template>
  <div class="subject-content">

    <!--  头工具栏  -->
    <el-row :gutter="10" style="margin-bottom: 15px">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleDelete">删除</el-button>
      </el-col>
    </el-row>

    <!--  表格  -->
    <el-table v-loading="loading" :data="quartzList" style="width: 100%;" :cell-style="{padding:'0'}"
              :row-style="{height:'60px'}" @selection-change="handleSelectionChange">
      <el-table-column fixed="left" type="selection" width="50" align="center"></el-table-column>
      <el-table-column prop="jobId" label="任务ID" width="110" sortable align="center" fixed="left"></el-table-column>
      <el-table-column prop="jobName" label="定时名称" width="120" sortable align="center"></el-table-column>
      <el-table-column prop="jobGroup" label="任务组名" width="110" sortable align="center">
        <template v-slot="scope">
          <dictTag :options="dict.dictType.job_group" :value="scope.row.jobGroup"></dictTag>
        </template>
      </el-table-column>
      <el-table-column prop="invokeTarget" label="调用目标字符串" align="center"></el-table-column>
      <el-table-column prop="cronExpression" label="cron执行表达式" align="center"></el-table-column>
      <el-table-column prop="jobStatus" label="状态" width="110" sortable align="center">
        <template v-slot="scope">
          <el-switch v-model="scope.row.jobStatus"
                     active-color="red"
                     inactive-color="#13ce66"
                     active-value="0"
                     inactive-value="1"
                     @change="handleIsPopularizeChange(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" sortable align="center"></el-table-column>
      <el-table-column prop="updateTime" label="更新时间" sortable align="center"></el-table-column>
      <el-table-column fixed="right" label="操作" width="180" align="center">
        <!-- 固定列需要使用fixed属性，它接受 Boolean 值或者left right，表示左边固定还是右边固定。 -->
        <template  v-slot="scope">
          <el-button type="text" size="small" icon="el-icon-edit" @click="rowUpdate(scope.row)">修改</el-button>
          <el-button type="text" size="small" icon="el-icon-delete" @click="rowDelete(scope.row)">删除</el-button>

          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
            <span class="el-dropdown-link"><i class="el-icon-d-arrow-right el-icon--right"></i>更多</span>
            <el-dropdown-menu v-slot="dropdown">
              <el-dropdown-item command="handleRun" icon="el-icon-caret-right">执行一次</el-dropdown-item>
              <el-dropdown-item command="handleView" icon="el-icon-view">任务详细</el-dropdown-item>
              <el-dropdown-item command="handleJobLog" icon="el-icon-s-operation">调度日志</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>

    </el-table>
    <!--  分页  -->
    <page
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.current"
        :limit.sync="queryParams.size"
        @pagination="getList"
    />


    <!-- 添加或修改用户 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>

      <el-form ref="quartzForm" :model="quartzForm" :rules="rules" size="small" label-width="150px">

        <el-form-item label="任务名称" prop="jobName">
          <el-input v-model="quartzForm.jobName" placeholder="请输入任务名称" clearable></el-input>
        </el-form-item>

        <el-form-item label="任务分组" prop="jobGroup">
          <el-select v-model="quartzForm.jobGroup" placeholder="请输入任务分组" clearable>
            <el-option v-for="(item, index) in dict.dictType.job_group" :key="index" :label="item.dictLabel"
                       :value="item.dictValue"/>
          </el-select>
        </el-form-item>

        <el-form-item prop="invokeTarget">
              <span slot="label">
                调用目标字符串
                <el-tooltip placement="top">
                  <div slot="content">
                    Bean调用示例：lyTask.lyParams('ly')
                    <br/>Class类调用示例：com.lingyun.system.quartz.LyTask.lyParams('ly')
                    <br/>参数说明：支持字符串，布尔类型，长整型，浮点型，整型
                  </div>
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
          <el-input v-model="quartzForm.invokeTarget" placeholder="请输入调用目标字符串" clearable></el-input>
        </el-form-item>

        <el-form-item label="cron执行表达式" prop="cronExpression">
          <el-select v-model="quartzForm.cronExpression" placeholder="请输入cron执行表达式" clearable>
            <el-option v-for="(item, index) in dict.dictType.cron_expression" :key="index" :label="item.dictLabel"
                       :value="item.dictValue"/>
          </el-select>
        </el-form-item>

        <el-form-item label="执行策略" prop="misfirePolicy">
          <el-radio-group v-model="quartzForm.misfirePolicy" size="small">
            <el-radio-button label="1">立即执行</el-radio-button>
            <el-radio-button label="2">执行一次</el-radio-button>
            <el-radio-button label="3">放弃执行</el-radio-button>
            <el-radio-button label="4">执行一次删除</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否并发" prop="concurrent">
          <el-radio-group v-model="quartzForm.concurrent" size="small">
            <el-radio-button label="0">允许</el-radio-button>
            <el-radio-button label="1">禁止</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="状态" prop="jobStatus">
          <el-radio-group v-model="quartzForm.jobStatus" size="medium">
            <el-radio v-for="(item, index) in dict.dictType.job_status" :key="index" :label="item.dictValue">
              {{ item.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!--        <el-form-item label="cron执行表达式" prop="cronExpression">-->
        <!--          <el-input v-model="quartzForm.cronExpression" placeholder="请输入cron执行表达式">-->
        <!--            <template slot="append">-->
        <!--              <el-button type="primary" @click="handleShowCron">生成表达式<i class="el-icon-time el-icon&#45;&#45;right"></i></el-button>-->
        <!--            </template>-->
        <!--          </el-input>-->
        <!--        </el-form-item>-->

      </el-form>

      <div slot="footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>

    </el-dialog>

  </div>
</template>

<script>
import Page from "@/components/page.vue";
import {
  getQuartzById,
  getQuartzList,
  quartzAdd,
  quartzDelete,
  quartzIds,
  quartzUpdate,
  updateJobStatus
} from "@/api/admin/quarzt";
import dictTag from "@/components/dictTag.vue";

export default {
  name: "quartz",
  dicts: ["job_group", "cron_expression", "job_status"],
  components: {dictTag, Page},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: "",
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      // 查询参数  current 当前页   size 页大小
      queryParams: {
        current: 1,
        size: 10,
      },

      //表格数据
      quartzList: [],
      // 表单参数
      quartzForm: {},
      // 表单数据校验
      rules: {

        jobName: [{required: true, message: "任务名称不能为空", trigger: "blur"}],
        jobGroup: [{required: true, message: "请选择任务分组", trigger: "change"}],
        invokeTarget: [{required: true, message: "调用目标字符串不能为空", trigger: "change"}],
        cronExpression: [{required: true, message: '请输入cron执行表达式', trigger: 'change'}],

      },

    }
  },
  methods: {

    // 根据条件分页查询定时任务列表
    getList() {
      getQuartzList(this.queryParams).then(res => {
        this.quartzList = res.data.records;
        this.total = res.data.total;
        this.loading = false;
      })
    },

    // 重置表单
    reset() {
      this.quartzForm = {
        // 任务id
        jobId: undefined,
        //任务名称
        jobName: undefined,
        //任务分组
        jobGroup: undefined,
        //调用目标字符串
        invokeTarget: undefined,
        //cron执行表达式
        cronExpression: undefined,
        //执行策略
        misfirePolicy: "3",
        //是否并发
        concurrent: "0",
        //状态
        jobStatus: "0",
      };
      this.resetForm("quartzForm");
    },

    // 头工具栏--添加
    handleAdd() {
      this.reset();
      this.title = "添加定时任务";
      this.open = true;
    },

    // 头工具栏--修改
    handleUpdate() {
      if (this.ids.length === 0) {
        this.$modal.msgWarning('请选择要修改的定时任务！')
      } else if (this.ids.length > 1) {
        this.$modal.msgWarning('请选择一个定时任务进行修改！')
      } else {
        this.reset();
        const jobId = this.ids;
        getQuartzById(jobId).then(res => {
          this.quartzForm = res.data;
          this.title = "修改定时任务"
          this.open = true;
        })
      }
    },

    // 头工具栏--删除
    handleDelete() {
      const data = this.ids;
      this.$modal.confirm("是否确认删除？").then(function () {
        return quartzIds(data)
      }).then(res => {
        this.getList();
        this.$modal.msgSuccess(res.msg);
      })
    },

    // 提交按钮
    submitForm: function () {
      this.$refs.quartzForm.validate(valid => {
        if (valid) {  // 表单不为空，valid为真
          if (this.quartzForm.jobId != undefined) {
            quartzUpdate(this.quartzForm).then(res => {
              this.$modal.msgSuccess(res.msg);
              this.open = false;
              this.getList();
            })
          } else {
            quartzAdd(this.quartzForm).then(res => {
              this.$modal.msgSuccess(res.msg);
              this.open = false;
              this.getList();
            })
          }
        }
      })
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 行工具--修改
    rowUpdate(row) {
      this.reset();
      const jobId = row.jobId;
      getQuartzById(jobId).then(res => {
        this.quartzForm = res.data;
        this.title = "修改定时任务"
        this.open = true;
      })
    },

    // 行工具--删除
    rowDelete(row) {
      const jobId = row.jobId
      this.$modal.confirm('是否确认删除？').then(function () {
        return quartzDelete(jobId);
      }).then(res => {
        this.getList();
        this.$modal.msgSuccess(res.msg)
      })
    },

    // 修改定时任务状态
    handleIsPopularizeChange(row) {
      let text = row.jobStatus === "0" ? "停用" : "执行定时任务";
      this.$modal.confirm("确认要" + text + " “" + row.jobName + "“ ”" + "吗？").then(function () {
        return updateJobStatus(row.jobId, row.jobStatus)
      }).then(res => {
        this.$modal.msgSuccess(res.msg);
      }).catch(function () {
        row.jobStatus = row.jobStatus === "0" ? "1" : "0";
      });
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleRun":
          this.handleRun(row);  // 执行一次
          break;
        case "handleView":
          this.handleView(row);  // 任务详情
          break;
        case "handleJobLog":
          this.handleJobLog(row); //任务日志
          break;
        default:
          break;
      }
    },

    //执行一次
    handleRun(row) {
      alert("执行一次")
    },

    //任务详情
    handleView(row) {
      alert("任务详情")
    },

    //任务日志
    handleJobLog(row) {
      alert("任务日志")
    },


    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.jobId)
    },

  },
  created() { // 初始化
    this.getList();
  }

}
</script>

<style scoped>
.el-row {
  display: inline-block;
}

.el-form-item {
  display: inline-block;
}


/deep/ .el-dialog {
  position: fixed !important;
  right: 0 !important;
  top: 0 !important;
  z-index: 2500 !important;
  margin-top: 0 !important;
  height: 100%;
}
</style>
